<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="isUpdate ? t('common.edit') : t('common.create')"
      @register="register"
      @ok="handleSubmit"
      @cancel="clearForm"
      :destroyOnClose="true"
      :minHeight="400"
      :width="1000"
    >
      <partDetail
        ref="partDetailRef"
        :isUpdate="isUpdate"
        :folderId="folderId"
        :partType="partType"
        :currentRecord="currentRecord"
      />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, inject } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  const isUpdate = ref<boolean>(false); // 是否是编辑
  const folderId = ref<string>(''); // 文件夹id
  const partType = ref<string>(''); // 文件夹类型
  const currentRecord = ref<any>({}); // 当前记录
  const partDetailRef = ref(); // 引用 partDetail 组件

  import partDetail from './components/partDetail.vue';

  import { AddPartAndFile, UpdatePart } from '/@/api/demo/partManager';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['register', 'success', 'addSuccess']);

  // 提交
  async function handleSubmit() {
    // 调用partDetailRef.value的valiDateFormData方法，获取验证结果
    await partDetailRef.value?.valiDateFormData();

    setModalProps({ confirmLoading: true });
    try {
      // 成功
      const params = await partDetailRef.value?.getFormData();
      if (isUpdate.value) {
        await UpdatePart(params);
        createMessage.success(t('common.editSuccessText'));
        emit('success');
        clearForm();
      } else {
        await AddPartAndFile(params);
        createMessage.success(t('common.addSuccessText'));
        emit('addSuccess');
        clearForm();
      }
    } finally {
      setModalProps({ confirmLoading: false });
      clearForm();
    }
  }

  const clearForm = () => {
    closeModal();
  };

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    folderId.value = data?.FolderId;
    partType.value = data?.partType;
    currentRecord.value = data?.currentRecord;
  });
</script>

<style lang="less" scoped></style>
